<?php

namespace app\common\model\mysql;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class BaseModel extends Model
{

    /**
     * 自动生成写入时间
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 通过id更新信息
     * @param $id
     * @param $data
     * @return bool
     */
    public function updateById($id, $data)
    {
        $id = intval($id);
        if (empty($id) || empty($data) || !is_array($data)) {
            return false;
        }

        $data['update_time'] = time();

        $where = [
            "id" => $id
        ];
        return $this->where($where)->save($data);
    }

    /**
     * 新增/更新数据
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function saveData($data): bool
    {
        $db=$this;
        if(isset($data['id'])){
            $db=$this->find($data['id']);
            if(empty($db)){
                throw new Exception('数据不存在');
            }
        }
        return $db->save($data);
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     */
    public function deleteById($id): bool
    {
        return $this->where(['id'=>$id])->delete();
    }

    /**
     * 根据id修改状态
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function updateStatus($data): bool
    {
        $row=$this->find($data['id']);
        if(empty($row)){
            throw new Exception('数据不存在');
        }
        return $row->save(['status'=>$data['status']]);
    }

    /**
     * 获取分页列表
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTableList($where,$page,$limit): array
    {
        if(!empty($page)&&!empty($limit)){
            $list=$this->page($page,$limit)->where($where)->order('id desc')->select();
        }else{
            $list=$this->where($where)->order('id desc')->select();
        }
        $list=$list->isEmpty()?[]:$list->toArray();
        $count=$this->where($where)->count();
        return ['count'=>$count,'list'=>$list];
    }

    /**
     * @param array $where
     * @param array $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getChartList(array $where=[], array $field=[]): array
    {
        if(isset($this->schema['status'])){
            $where[]=['status','=',config("status.mysql.table_normal")];
        }
        $data=$this->where($where)->field($field)->select();
        return $data->isEmpty()?[]:$data->toArray();
    }
}
